import React, { Component, Fragment } from 'react'
import { Button, Table, Pagination, Checkbox, message, Modal, Popover, Spin, Row, Col, Divider, Empty } from 'antd'
import _ from 'lodash'
import moment from 'moment'
import FileSaver from 'file-saver'

import { address } from '@/Utils/apiConfig.js'
import Event from '@/Utils/Event'
import { Certificate_Status } from '@/Utils/CONST'
import { ISSUECERTIFICATE, CERTREVOKE, CERTUPDATE, CERTFROZEN, CERTUNFROZEN } from '@/Utils/socketName'
import request from '@/Utils/fecth'
import IconFont from '@/components/IconFont'
import SearchInput from '@/components/SearchInput'
import Clamp from '@/components/Clamp'
import { checkPermission } from '@/components/AuthComponent/utils'

import CreateModal from './create.js'

import './index.less'

const { organizationManagement: { certificateList, download, searchCer,
  revokeCert, certificateFrozen, certificateUnfrozen, certificateDetail }} = address

const SORT = {
  'ascend': 'asc',
  'descend': 'desc',
}

class Certificate extends Component {
  constructor(props) {
    super(props)
    this.state = {
      pageNo: 1, // 当前页
      pageSize: 10, // 每页的条数
      sort: 'asc',
      listData: [],
      loading: false,
      modalLoading: false,
      statusList: _.cloneDeep(Certificate_Status),
      showCreateModal: false,
      detailModalVisible: false,
      typeList: [
        { id: 'client', text: 'client', checked: false },
        { id: 'admin', text: 'admin', checked: false },
      ],
      totalNum: 0,
      currentFilter: '',
      certType: [],
      status: [],
      columns: [],
      applySort: false,
      revokeSort: false,
    }
    this.handleRecord = {}
    this.detailInfo = {}
    this.flag = 'create'
  }

  get columns() {
    const { applySort, revokeSort } = this.state
    return [
      {
        title: '证书标识',
        dataIndex: 'identity',
        key: 'identity',
      },
      {
        title: '证书类型',
        dataIndex: 'type',
        key: 'type',
        width: 130,
        className: 'type',
        onFilterDropdownVisibleChange: visible => {
          if (document.getElementsByClassName('type') && document.getElementsByClassName('type').length) {
            document.getElementsByClassName('type')[0].style.backgroundColor = visible ? '#F1F3F4' : '#F8F8F8'
          }
          if (visible) {
            this.setState({ currentFilter: 'typeList' })
          } else {
            this.setState({ currentFilter: '' })
          }
        },
        filterDropdown: ({
          setSelectedKeys, selectedKeys, confirm, clearFilters,
        }) => {
          return (
            this.dropDown(setSelectedKeys, clearFilters, confirm, 'typeList', selectedKeys)
          )
        },
      },
      {
        title: '状态',
        width: 94,
        dataIndex: 'status',
        key: 'status',
        className: 'status',
        onFilterDropdownVisibleChange: visible => {
          if (document.getElementsByClassName('status') && document.getElementsByClassName('status').length) {
            document.getElementsByClassName('status')[0].style.backgroundColor = visible ? '#F1F3F4' : '#F8F8F8'
          }
          if (visible) {
            this.setState({ currentFilter: 'statusList' })
          } else {
            this.setState({ currentFilter: '' })
          }
        },
        filterDropdown: ({
          setSelectedKeys, selectedKeys, confirm, clearFilters,
        }) => {
          return (
            this.dropDown(setSelectedKeys, clearFilters, confirm, 'statusList', selectedKeys)
          )
        },
        render: (text) => {
          const { statusList } = this.state
          const item = (statusList.find(v => v.id === text) || {})
          return <div className={item.className || ''}>
            {
              item.text || '--'
            }
          </div>
        },
      },
      {
        title: '申请日期',
        key: 'apply_date',
        dataIndex: 'apply_date',
        sorter: true,
        sortOrder: applySort,
        render: (text) => <span>{text ? moment(text).format('YYYY.MM.DD HH:mm:ss') : ''}</span>,
      },
      {
        title: '失效日期',
        key: 'revoke_date',
        dataIndex: 'revoke_date',
        sorter: true,
        sortOrder: revokeSort,
        render: (text) => <span>{text ? moment(text).format('YYYY.MM.DD HH:mm:ss') : ''}</span>,
      },
      {
        title: '公钥密码算法',
        dataIndex: 'algorithm',
        key: 'algorithm',
      },
      {
        title: '操作',
        key: 'operate',
        render: (text, record) => {
          return <Fragment>
            {
              checkPermission('org-certificate-download') &&
              <span
                className={`common-operation ${!['SUCCESS'].includes(record.status) ? 'disabled' : ''}`}
                onClick={() => { this.download(record.id, record.status) }}>下载</span>
            }

            <Popover overlayClassName="handle-popover" placement="bottom" content={
              <div className="popover-handle-content">
                {
                  checkPermission('org-certificate-detail') &&
                  <p
                    className="popover-handle-item primary cursor"
                    onClick={() => this.showDetail(record)}
                  >
                  查看证书
                  </p>
                }

                {
                  checkPermission('org-certificate-update') &&
                  ['SUCCESS', 'UPDATE_FAILED'].includes(record.status) &&
                  <p
                    className="popover-handle-item primary cursor"
                    onClick={() => this.update(record)}
                  >
                    修改证书
                  </p>
                }
                {
                  checkPermission('org-certificate-frozen') &&
                  ['SUCCESS', 'FROZEN'].includes(record.status) &&
                  <p className="popover-handle-item primary cursor" onClick={() => this.handleFrozen(record)}>
                    {record.status === 'FROZEN' ? '解冻' : '冻结'}证书
                  </p>
                }
                {
                  checkPermission('org-certificate-revoke') &&
                  ['SUCCESS', 'CANCEL_FAILED'].includes(record.status) &&
                  <p className="popover-handle-item primary cursor">
                    <span className={`common-operation`} onClick={() => this.cancel(record)}>注销证书</span>
                  </p>
                }
              </div>
            }>
              <span className="common-operation">
                更多<IconFont style={{ marginLeft: '4px' }} className="cursor" type="ic-down" />
              </span>
            </Popover>
          </Fragment>
        },
      },
    ]
  }

  componentDidMount() {
    this.getData()
    Event.on(ISSUECERTIFICATE, this.getData)
    Event.on(CERTREVOKE, this.getData) // 吊销证书
    Event.on(CERTUPDATE, this.getData) // 修改证书
    Event.on(CERTFROZEN, this.getData) // 冻结证书
    Event.on(CERTUNFROZEN, this.getData) // 解冻证书
  }

  componentWillUnmount() {
    Event.off(ISSUECERTIFICATE, this.getData)
    Event.off(CERTREVOKE, this.getData)
    Event.off(CERTUPDATE, this.getData)
    Event.off(CERTFROZEN, this.getData)
    Event.off(CERTUNFROZEN, this.getData)
  }

  getData = async() => {
    const { id } = this.props
    const { pageNo, pageSize, sort, certType, status, columns } = this.state
    const option = {
      orgId: id,
      pageNum: pageNo,
      pageSize,
    }
    let body = {
      columns,
      sort,
    }

    if (certType.length) {
      body.certType = certType
    }
    if (status.length) {
      body.status = status
    }
    this.setState({
      loading: true,
    })
    let { status: _status, data = {}} = await request().get(certificateList.format({ ...option }), body)
    this.setState({
      loading: false,
    })
    if (_status === 200) {
      this.totalList = data.certList || []
      this.totalNumer = data.totalNum || 0
      this.setState({
        listData: data.certList || [],
        totalNum: data.totalNum || 0,
      })
    }
  }

  /**
   * 创建证书
   */
  create = () => {
    this.flag = 'create'
    this.handleRecord = {}
    this.setState({
      showCreateModal: true,
    })
  }

  /**
   *
   * @param {修改证书} record
   */
  update = (record) => {
    this.handleRecord = record
    this.flag = 'update'
    this.setState({
      showCreateModal: true,
    })
  }

  /**
   * 查看证书
   */
  showDetail = async(record) => {
    this.handleRecord = record
    this.setState({
      modalLoading: true,
      detailModalVisible: true,
    })
    const { status, data } = await request().get(certificateDetail.format({ id: record.id }))
    if (status === 200) {
      const infoList = ((data || {}).attributes || '').split(',').reduce((arr, v) => {
        const [first, last] = v.replace(':ecert', '').split('=')
        first && last && arr.push({
          first,
          last,
        })
        return arr
      }, [])
      this.detailInfo = {
        ...(data || {}),
        infoList,
      }
      this.setState({
        modalLoading: false,
      })
    }
  }

  /**
   * 冻结/解冻证书
   * @param {*} record
   */
  handleFrozen = (record) => {
    this.handleRecord = record
    Modal.confirm({
      title: `确定要${record.status === 'FROZEN' ? '解冻' : '冻结'}该证书吗？`,
      content: `${record.status === 'FROZEN' ? '解冻后该证书将可以再发起交易，请谨慎操作' : '冻结后该证书将不再发起交易，请谨慎操作'}`,
      onOk: async() => {
        const { id } = this.props
        const { status } = await request().post(record.status === 'FROZEN' ? certificateUnfrozen : certificateFrozen, {
          orgId: id,
          certId: record.id,
          identityType: record.type,
          identityName: record.identity,
        })
        if (status === 200) {
          message.success(`证书${record.status === 'FROZEN' ? '解冻' : '冻结'}中`)
          this.getData()
        }
      },
    })
  }

  handleTableChange = (pagination, filters, sorter) => {
    // 筛选功能
    let status = []
    let certType = []
    if (filters.status) {
      filters.status && filters.status.map(item => status.push(item.id))
    }
    if (filters.type) {
      filters.type && filters.type.map(item => certType.push(item.id))
    }
    this.setState({
      status,
      certType,
      pageNo: 1,
    }, () => {
      this.getData()
    })

    // 排序功能
    if (sorter) {
      const field = sorter.field
      let { applySort, revokeSort } = this.state
      let sort = null
      if (field === 'apply_date') {
        applySort = applySort === false ? 'ascend' : applySort === 'ascend' ? 'descend' : false
        sort = SORT[applySort]
        revokeSort = false
      } else if (field === 'revoke_date') {
        revokeSort = revokeSort === false ? 'ascend' : revokeSort === 'ascend' ? 'descend' : false
        sort = SORT[revokeSort]
        applySort = false
      }
      this.setState({
        columns: [field],
        applySort,
        revokeSort,
        sort,
      })
    }
  }

  // 筛选下拉列表
  dropDown = (setSelectedKeys, clearFilters, confirm, varName, selectedKeys) => {
    return (
      <div >
        <div className="ant-dropdown-menu" >
          {
            this.state[varName].map((element, index) => {
              return (
                <li className="ant-dropdown-menu-item" key={element.text}
                  onClick={() => this.selectLevel(element, index, varName, setSelectedKeys)}
                >
                  <Checkbox checked={element.checked}> <span style={{ color: '#171E2D' }}>{element.text}</span></Checkbox>
                </li>
              )
            })
          }
        </div>
        <div className="ant-table-filter-dropdown-btns">
          <span className="clear"
            onClick={() => this.clear(clearFilters, varName)}
          >
            重置</span>
          <span className="confirm"
            onClick={() => this.confirm(confirm, selectedKeys)}
          >确定</span>

        </div>
      </div>
    )
  }
  // 筛选的勾选操作
  selectLevel = (level, index, flag, setSelectedKeys) => {
    // 设置选择的key
    this.level = _.cloneDeep(level)
    let data = this.state[flag]

    data[index].checked = !level.checked

    this.setState({
      [flag]: data,
    })
    setSelectedKeys(data.filter(element => { return element.checked === true }))
    // this.confirm(null, flag)
  }

  // 手动确定
  confirm = (confirm, selectedKeys) => {
    confirm && confirm()
  }

  // 重置 重置为初始状态
  clear = (clear, flag) => {
    let data = this.state[flag]
    data.map(element => {
      element.checked = false
    })
    this.setState({
      [flag]: data,
    })
    clear()
  }

  onShowSizeChange = (current, pageSize) => {
    let pageNo = this.state.pageNo
    if (this.state.listData.length < pageNo * pageSize) {
      pageNo = Math.ceil(this.state.listData.length / pageSize) || 1
    }
    this.setState({
      pageSize,
      pageNo,
    })
  }

  changePaginationFn = (pageNumber) => {
    this.setState({
      pageNo: pageNumber,
    }, () => {
      this.getData()
    })
  }

  search = (val) => {
    const { id } = this.props
    if (!val) {
      this.getData()
    } else {
      const ops = {
        key: val,
        orgId: id,
      }
      request().post(searchCer, ops).then(res => {
        if (res.status === 200) {
          this.setState({
            listData: res.data,
            totalNum: res.data.length,
            pageNo: 1,
            applySort: false,
            revokeSort: false,
          })
        }
      })
    }
  }

  download = (id, status) => {
    const obj = {
      'CREATING': '该证书在创建中，不支持下载',
      'FAILED': '该证书创建失败，不支持下载',
      'CANCEL': '该证书已注销，不支持下载',
    }
    if (status !== 'SUCCESS') {
      message.warn(obj[status] || '下载失败')
      return
    }
    request().get(download.format({ certId: id }), {
      responseType: 'blob',
    }).then(res => {
      const status = res.status
      if (status === 200) {
        FileSaver.saveAs(res.data, 'cert.zip')
      }
    })
  }

  createCerClose = () => {
    this.setState({
      showCreateModal: false,
    })
    this.getData()
  }

  /**
   * 注销证书
   * @param {*} record
   */
  cancel = async(record) => {
    Modal.confirm({
      title: `是否要注销该${record.type}证书？`,
      content: '注销后该证书即失效，不可再恢复',
      onOk: async() => {
        const { id } = this.props
        const { status } = await request().post(revokeCert, {
          orgId: id,
          certId: record.id,
          identityType: record.type,
          identityName: record.identity,
        })
        if (status === 200) {
          this.getData()
          message.success('操作成功')
        }
      },
    })
  }

  render() {
    const { showCreateModal, listData, totalNum, loading, detailModalVisible, modalLoading, statusList } = this.state
    const { id } = this.props
    return (
      <div id="certificate-page" className="certificate-page common">
        <div className="container">
          <div className="operate">
            {
              checkPermission('org-certificate-create') &&
            <Button type="primary" onClick={this.create}>创建证书</Button>
            }
            <SearchInput
              placeholder="请输入证书ID"
              search={this.search}
            />
          </div>
          <div className="table-list">
            <div className="peer_wrapper">
              <Table
                loading={loading}
                columns={this.columns}
                onChange={this.handleTableChange}
                className={listData.length ? '' : 'empty-list'}
                dataSource={listData}
                rowKey="id"
                pagination={false}
                locale={{
                  emptyText: <span> </span>,
                }}
              />
              {
                !listData.length &&
                <Empty />
              }
            </div>
            <div className="pagination-box">
              {
                listData.length > 0 &&
                <Pagination
                  current={this.state.pageNo}
                  pageSize={this.state.pageSize}
                  showSizeChanger
                  showQuickJumper
                  onShowSizeChange={this.onShowSizeChange}
                  total={totalNum}
                  onChange={this.changePaginationFn} />
              }
            </div>
          </div>
        </div>
        {
          showCreateModal &&
          <CreateModal
            orgId={id}
            record={this.handleRecord}
            flag={this.flag}
            createCerClose={this.createCerClose}
            visible={showCreateModal} />
        }
        <Modal
          className="detail-modal"
          getContainer={() => document.getElementById('certificate-page')}
          title={`查看证书`}
          visible={detailModalVisible}
          onOk={() => this.setState({ detailModalVisible: false })}
          onCancel={() => this.setState({ detailModalVisible: false })}
          centered
          width={900}
        >
          <Spin spinning={modalLoading}>
            {
              this.detailInfo.id &&
              <div className="detail-content">
                {
                  <Row className="desc-item" gutter={[16, 16]}>
                    <Col span={8}>
                      <span className="label">证书类型:</span>
                      <span title={this.detailInfo.type || '--'} className="value">{this.detailInfo.type || '--'}</span>
                    </Col>
                    <Col span={8}>
                      <span className="label">证书标识:</span>
                      <span title={this.detailInfo.identity || '--'} className="value">{this.detailInfo.identity || '--'}</span>
                    </Col>
                    <Col span={8}>
                      <span className="label">证书状态:</span>
                      <span className="value">{
                        (statusList.find(v => v.id === this.detailInfo.status) || {}).text || '--'
                      }</span>
                    </Col>
                    <Col span={8}>
                      <span className="label">申请日期:</span>
                      <span className="value">{this.detailInfo.apply_date ? moment(this.detailInfo.apply_date).format('YYYY.MM.DD HH:mm:ss') : '--'}</span>
                    </Col>
                    <Col span={8}>
                      <span className="label">失效日期:</span>
                      <span className="value">{this.detailInfo.revoke_date ? moment(this.detailInfo.revoke_date).format('YYYY.MM.DD HH:mm:ss') : '--'}</span>
                    </Col>
                    <Col span={8}>
                      <span className="label">公钥加密算法:</span>
                      <span title={this.detailInfo.algorithm || '--'} className="value">{this.detailInfo.algorithm || '--'}</span>
                    </Col>
                  </Row>
                }
                <Divider plain >证书信息</Divider>
                {
                  this.detailInfo.infoList.length > 0 &&
                  <Row className="desc-item" gutter={[16, 16]}>
                    {
                      this.detailInfo.infoList.map((v, i) => {
                        return <Col key={i} span={8}>
                          <span className="label">
                            <Clamp content={v.first + ':'} length={16}/>
                          </span>
                          <span className="value">
                            <Clamp content={v.last} length={16} />
                          </span>
                        </Col>
                      })
                    }
                  </Row>
                }
                {
                  !this.detailInfo.infoList.length &&
                  <Empty />
                }
              </div>
            }
          </Spin>
        </Modal>
      </div>
    )
  }
}

export default Certificate
